<?php

namespace App\Http\Controllers\Salerule;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Salerule\Salerule;
use App\Models\Company as ModelsCompany;
use Illuminate\Http\Request;
use App\Models\Salerule\Salerule as ModelSalerule;

/**
 * 销售规则设置管理
 */
class SaleruleController extends BaseController
{
    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only([
            'id',
            'pieces_min',
            'pieces_max',
            'weight_min',
            'weight_max',
            'extra_type'
        ]);
        $validate = new Salerule('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        if (empty($req_data['pieces_min'])) {
            $data = [
                'extra_type' => $req_data['extra_type'],
                'update_at' => time(),
            ];
        } else {
            $data = [
                'pieces_min' => $req_data['pieces_min'],
                'pieces_max' => $req_data['pieces_max'],
                'weight_min' => mathfuncweight('mul', $req_data['weight_min'], 10000),
                'weight_max' => mathfuncweight('mul', $req_data['weight_max'], 10000),
                'update_at' => time(),
            ];
        }

        ModelSalerule::where([['id', $req_data['id']]])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 获取子账套销售规则
     */
    public function getone()
    {
        $cpid = $this->mangerinfo['cpid'] ?? 0;
        $res = ModelSalerule::where('cpid', $cpid)->first();
        if ($res) {
            $res = $res->toArray();
            $res['weight_min'] = $res['weight_min'] / 10000;
            $res['weight_max'] = $res['weight_max'] / 10000;
            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $res]);
        } else {
            return response()->json(['code' => '001', 'msg' => '操作成功', 'data' => []]);
        }
    }

    /**
     * 获得账套信息
     */
    public function getcpid()
    {
        $cpid = $this->mangerinfo['cpid'] ?? 0;
        $one = ModelsCompany::where('id', $cpid)->first()->toArray();
        if ($one) {
            $one = $one->toArray();
            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
        } else {
            return response()->json(['code' => '001', 'msg' => '操作成功', 'data' => []]);
        }
    }
}
